use wasm_bindgen::JsCast;
use web_sys::{HtmlElement};

pub fn add_class(id: &str, class_name: &str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            if let Some(element) = document.get_element_by_id(id) {
                let class_list = element.class_list();
                class_list.add_1(class_name).expect("add class error");
            }
        }
    }
}

pub fn remove_class(id: &str, class_name: &str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            if let Some(element) = document.get_element_by_id(id) {
                let class_list = element.class_list();
                class_list.remove_1(class_name).expect("remove class error");
            }
        }
    }
}

pub fn clean_class(id: &str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            if let Some(element) = document.get_element_by_id(id) {
                let class_list = element.class_list();
                class_list.remove_0().expect("remove class error");
            }
        }
    }
}

pub fn set_class_style(id: &str, style: &str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            if let Some(element) = document.get_element_by_id(id) {
                let element = element.dyn_into::<HtmlElement>().unwrap();
                let styles = element.style();
                styles.set_css_text(style);
            }
        }
    }
}

pub fn set_disabled(id: &str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            if let Some(element) = document.get_element_by_id(id) {
                let element = element.dyn_into::<HtmlElement>().unwrap();
                element.set_attribute("disabled", "").expect("disabled");
            }
        }
    }
}


pub fn set_enable(id: &str) {
    let element = get_element_as::<HtmlElement>(id);
    if let Some(element) = element {
        element.remove_attribute("disabled").unwrap()
    }
}

fn get_element_as<T: JsCast>(element_id: &str) -> Option<T> {
    web_sys::window()?
        .document()?
        .get_element_by_id(element_id)?
        .dyn_into::<T>()
        .ok()
}